﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TC.WEB.Site.Models.Tools;
using System.Text.RegularExpressions;
using TC.WEB.Site.Core;
using TC.WEB.Site.Models;
using TC.WEB.Site.Core.Task;
using TC.SSO.Server.Core;

namespace TC.SSO.Server.Controllers
{
    /// <summary>
    /// 注册
    /// </summary>
    public class RegisterController : BaseController
    {
        const string SESSION_REGISTER_ID = "__session_register_userid";
        //
        // GET: /Register/

        public ActionResult Index(FormCollection fc)
        {
            if (this.IsMobile)
            {
                return Register("index-mobile", fc);
            }
            return View("index",fc);
        }

        private ActionResult Register(string viewName, FormCollection fc)
        {
            string action = fc["action"] ?? "";
            if (!action.ToLower().Equals("submit"))
            {
                return View(viewName);
            }

            string txtUserMobile = fc["txtUserMobile"];
            if (string.IsNullOrWhiteSpace(txtUserMobile))
            {
                ViewBag.Msg = "手机号不能为空";
                return View(viewName);
            }
            txtUserMobile = txtUserMobile.Trim();

            string txtUserPassword = fc["txtUserPassword"];
            if (string.IsNullOrEmpty(txtUserPassword))
            {
                ViewBag.Msg = "手机密码不能为空";
                return View(viewName);
            }

            string txtUserCompany = fc["txtUserCompany"];
            if (string.IsNullOrEmpty(txtUserCompany))
            {
                ViewBag.Msg = "公司名称不能为空";
                return View(viewName);
            }

            
            string txtPhoneCode = fc["txtPhoneCode"] ?? "";
            if (!ValidCode.IsValid(txtUserMobile, txtPhoneCode))
            {
                ViewBag.Msg = "手机验证码不正确！";
                return View(viewName);
            }
             

            if (string.IsNullOrWhiteSpace(fc["selCompanyNature"]))
            {
                ViewBag.Msg = "工作性质不能为空！";
                return View(viewName);
            }

            Regex rx = new Regex("^(\\+([0-9]{1,6})|([0-9]{1,6}))?([\\-\\ ])?(\\d){1,4}?(\\-)?(\\d){7,8}(\\-)?(\\d){0,4}?$");
            if (rx.IsMatch(txtUserMobile))
            {
                var blank = BaseModel.M<UserBlankListModel>().CheckIsIn(txtUserMobile, 1);
                if (blank.Value)
                {
                    ViewBag.Msg = "该手机号码不可用！";
                    return View(viewName);
                }
                TC.WEB.Site.Models.UserModel um = BaseModel.M<TC.WEB.Site.Models.UserModel>();

                if (um.getUserNameByValue(new { UserMobile = txtUserMobile }) != null || um.getUserNameByValue(new { UserName=txtUserMobile }) != null)//手机号是否已经存在
                {
                    ViewBag.Msg = "手机号已经被注册，请重新填写！";
                    return View(viewName);
                }

                dynamic outUser = null;
                int uid = um.registerUser(txtUserMobile, txtUserPassword
                    , txtUserMobile, "gcdx", fc["selCompanyNature"] ?? "", fc["txtUserMobile"] ?? "", "", out outUser);
                if (uid > 0)
                {
                    ValidCode.Destroy();

                    //登录
                    string msgtemp = System.Configuration.ConfigurationManager.AppSettings["VcodeMsgRegisterSendPwTemplate"];
                    string msg = string.Format(msgtemp, txtUserPassword);
                    SMSSendTask.CreateAndRun(txtUserMobile, msg);

                    return RedirectToAction("BuildNet", "Auth", new { redirect = Request["redirect"], state = Request["state"] });
                }
            }
            else
            {
                ViewBag.Msg = "手机号码格式不正确！";
            }
            return View(viewName);
        }

        public ActionResult Forgot(FormCollection fc)
        {
            if (this.IsMobile)
            {
                return CheckForgot("forgot-mobile", fc);
            }
            return this.CheckForgot("forgot", fc);
        }

        private ActionResult CheckForgot(string viewName, FormCollection fc)
        {
            string action = fc["action"] ?? "";
            if (!action.ToLower().Equals("submit"))
            {
                return View(viewName);
            }

            string txtUserMobile = fc["txtUserMobile"];
            if (string.IsNullOrWhiteSpace(txtUserMobile))
            {
                ViewBag.Msg = "手机号不能为空";
                return View(viewName);
            }
            txtUserMobile = txtUserMobile.Trim();

            string txtUserPassword = fc["txtUserPassword"];
            if (string.IsNullOrEmpty(txtUserPassword))
            {
                ViewBag.Msg = "手机密码不能为空";
                return View(viewName);
            }

           
           string txtPhoneCode = fc["txtPhoneCode"] ?? "";
           if (!ValidCode.IsValid(txtUserMobile, txtPhoneCode))
           {
               ViewBag.Msg = "手机验证码不正确！";
               return View(viewName);
           }
            

            var um = BaseModel.M<TC.WEB.Site.Models.UserModel>();

            string password = Tcbci.Security.MD5.EncryptString16(txtUserPassword);
            um.saveEq(new { UserPass = password }, new { UserMobile = txtUserMobile });

           return RedirectToAction("BuildNet", "Auth", new { redirect = Request["redirect"], state = Request["state"] });
        }

        /// <summary>
        /// 启用手机验证，注册时，发送验证码给用户
        /// </summary>
        /// <returns></returns>
        public ActionResult MobileCode(FormCollection form)
        {
            /*
            if (string.IsNullOrWhiteSpace(form["txtImageCode"]))
            {
                return this.JsonErrorResult("请输入图像验证码！");
            }
            else
            {
                if ((Session["vCode"] ?? "").ToString().ToLower() != form["txtImageCode"].ToLower())
                {
                    return this.JsonErrorResult("图像验证码不正确！");
                }
            }
             * */
            string result = string.Empty;
            string txtUserMobile = form["txtUserMobile"] ?? "";
            txtUserMobile = txtUserMobile.Trim();
            Regex rx = new Regex("^(\\+([0-9]{1,6})|([0-9]{1,6}))?([\\-\\ ])?(\\d){1,4}?(\\-)?(\\d){7,8}(\\-)?(\\d){0,4}?$");
            if (!rx.IsMatch(txtUserMobile))
            {
                return this.JsonErrorResult("手机号码格式不正确！");
            }
            var blank = BaseModel.M<UserBlankListModel>().CheckIsIn(txtUserMobile, 1);
            if (blank.Value)
            {
                return this.JsonErrorResult("该手机号码不可用！");
            }
            //验证用户名和密码是否存在
            TC.WEB.Site.Models.UserModel um = new TC.WEB.Site.Models.UserModel();

            dynamic dataUserName = um.getUserNameByValue(new { UserMobile = txtUserMobile });//通过手机号称获取用户ID
            if (dataUserName != null)//手机号是否已经存在
            {
                return this.JsonErrorResult("该手机号已被注册！");
            }
            string code = ValidCode.GenMobileCode(txtUserMobile);
            if (string.IsNullOrWhiteSpace(code))
            {
                return this.JsonErrorResult("请间隔1分钟！");
            }
            var smsLogModel = BaseModel.M<SystemSMSLogModel>();
            string[] ips = this.RemovteIps();
            foreach (string ip in ips)
            {
                if (smsLogModel.getIpCount(ip, DateTime.Now.Date, DateTime.Now.Date) > 20)
                {
                    return this.JsonErrorResult("您今天发送了太多的短信！");
                }
            }

            //修改注册发送短信验证码模板
            string msgtemp = System.Configuration.ConfigurationManager.AppSettings["VcodeMsgRegisterTemplate"];
            string msg = string.Format(msgtemp, code);
            SMSSendTask.CreateAndRun(txtUserMobile.Trim(), msg);
            foreach (string ip in ips)
            {
                smsLogModel.insertOne(ip, txtUserMobile.Trim(), DateTime.Now);
            }
            return this.JsonOkResult();
        }
    }
}
